<template>
  <div ref="chart" style="width: 200px; height: 200px"></div>
</template>

<script>
import * as echarts from "echarts";

export default {
  name: "EChartsExample",
  data() {
    return {
      dataPie: [
        { value: 35, name: "金属异物" },
        { value: 30, name: "石块 " },
        { value: 20, name: "木块 " },
        { value: 15, name: "其他 " },
      ],
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.initChart();
    });
  },
  methods: {
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      const myChart = echarts.init(this.$refs.chart);

      // 指定图表的配置项和数据
      const option = {
        title: {
          text: "告警类型分布",
          //   subtext: "Fake Data",
          left: "center",
          textStyle: {
            fontSize: 16,
            color: "#8c8c8c",
          },
        },
        tooltip: {
          trigger: "item",
        },
        legend: {
          //   orient: "horizontal",
          //   align: "left",
          //   bottom: "bottom",
          //   width: 100,
          textStyle: { color: "#fff" },
          orient: "vertical", // 设置为垂直布局
          itemGap: 2, // 每个 legend 项之间的间距
          bottom: "0", // 垂直方向上居中
          left: "left", // 水平方向上居中
          data: this.dataPie.map((item) => item.name),

          formatter: function (name) {
            // 找到对应的数据项
            var item = this.dataPie.find((i) => i.name === name);
            // 计算百分比
            var percent = item.value;
            return `${name} (${percent}%)`;
          }.bind(this),
        },
        series: [
          {
            // name: "Access From",
            type: "pie",
            radius: "70%",
            avoidLabelOverlap: false,
            label: {
              show: false,
              position: "center",
            },
            labelLine: {
              show: false,
            },
            data: this.dataPie,
            emphasis: {
              itemStyle: {
                shadowBlur: 10,
                shadowOffsetX: 0,
                shadowColor: "red",
              },
            },
          },
        ],
      };

      // 使用刚指定的配置项和数据显示图表。
      myChart.setOption(option);
    },
  },
};
</script>